package service

import (
	"github.com/gin-gonic/gin"
	"mojieshi/define"
	"mojieshi/models"
	"net/http"
	"time"
)

// 新增意见反馈
func AddOpinion(c *gin.Context) {
	var jsonData models.MOpinion
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonDataX, "")
		return
	}
	var data models.MOpinion
	data.Mid = jsonData.Mid
	data.Pics = jsonData.Pics
	data.Status = 1
	data.Content = jsonData.Content
	data.Tel = jsonData.Tel
	data.CreatedAt = int(time.Now().Unix())
	err = models.DB.Model(new(models.MOpinion)).Create(&data).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10001,
			"msg":  err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

// 获取意见列表
func GetOpinionList(c *gin.Context) {
	var jsonData Newdata
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	var list []models.MOpinion
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	tx := models.DB.Model(new(models.MOpinion)).Where("aid=? AND mid=?", jsonData.Aid, jsonData.Mid)
	if jsonData.Id > 0 {
		tx = tx.Where("id=?", jsonData.Id)
	}
	tx = tx.Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("id desc").Find(&list)
	if err != nil {
		define.Response.ResultFail(c, 10001, err.Error(), "")
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}
